package com.app.qtjk.lsh.service;
import java.sql.Timestamp;

import com.app.common.dataDictionary.DE.DE_EXT;
import com.app.common.dataDictionary.DE.DE_SIGN_COUNT;
import com.app.common.dataDictionary.DE.DE_SIGN_HISTORY;
import com.app.common.dataDictionary.DE.DE_SIGN_ID;
import com.app.common.dataDictionary.DE.DE_SIGN_LASTMODIFYTIME;
import com.app.common.dataDictionary.DE.DE_USERID;
import com.app.common.dataDictionary.DE.DE_USERWEALTH;
import com.app.common.dataDictionary.PO.TUserPO;
import com.app.common.dataDictionary.PO.TUserSignPO;
import com.app.common.utils.CollectionUtil;
import com.app.common.utils.DateFormatUtil;
import com.app.common.utils.MoveByteUtil;
import com.app.common.utils.ReqJsonUtil;
import com.app.common.utils.StringUtil;
import com.app.qtjk.common.util.ScoreRuleUtil;
import com.css.sword.kernel.base.annotation.Service;
import com.css.sword.kernel.base.annotation.ServiceContainer;
import com.css.sword.kernel.base.exception.SwordBaseCheckedException;
import com.css.sword.kernel.base.persistence.IPersistenceService;
import com.css.sword.kernel.base.persistence.SQLParam;
import com.css.sword.kernel.utils.SwordLogUtils;
import com.css.sword.kernel.utils.SwordPersistenceUtils;
import com.css.sword.kernel.utils.SwordSequenceUtils;
import com.css.sword.platform.web.event.IReqData;
import com.css.sword.platform.web.event.IResData;
import com.css.sword.platform.web.event.SwordRes;

@ServiceContainer
public class UserSignService {

	private static SwordLogUtils log = SwordLogUtils.getLogger(UserSignService.class);

	public UserSignService() throws Exception {
		super();
	}


	/**
	 * 检查用户是否签到过
	 * @param req
	 * @return
	 * @throws Exception
	 */
	@Service(serviceName = "UserSignService_checkSfSign")
	public IResData checkSfSign(IReqData req) throws Exception {
		
		log.debug("开始进入 UserSignService_checkSfSign 方法。");

		IPersistenceService dao = SwordPersistenceUtils.getPersistenceService();
		
		IResData res = new SwordRes();
		//获取前台post过来的数据
		String userid = ReqJsonUtil.getPostParam(req, "userId");
		SQLParam param = new SQLParam();
		param.addParam(userid);
		boolean signExist = false;
		String todayHaveSigned = "false";
		TUserSignPO userSignPO = dao.queryPOByKey("UserSignService_queryUserSignInfoByUserid", param, TUserSignPO.class);
		if (null != userSignPO && CollectionUtil.isNotBlankMap(userSignPO.toMap())) {
			signExist = true;
			String lastModifyTime = DateFormatUtil.date2str(userSignPO.getSignLastmodifytime().value,DateFormatUtil.DATE_FORMAT);
			Timestamp lastModifyTimeStamp = new Timestamp(DateFormatUtil.getTimeByDateStr(lastModifyTime, DateFormatUtil.DATE_FORMAT));
			Timestamp todayStartTimeStamp = new Timestamp(DateFormatUtil.getTimeByDateStr(DateFormatUtil.getNowDate(), DateFormatUtil.DATE_FORMAT));
			if (!todayStartTimeStamp.after(lastModifyTimeStamp)) {
				//今天没有签过到
				todayHaveSigned = "true";
			}
			final long missDays= (todayStartTimeStamp.getTime()-new Timestamp((lastModifyTimeStamp.getTime()+1)).getTime())/(24*60*60*1000);
			if (missDays > 0) {
				userSignPO.setSignCount(new DE_SIGN_COUNT(0));
				dao.updatePO(userSignPO);
			}
			res.put("todayHaveSigned", todayHaveSigned);
			res.put("signCount", StringUtil.parse2String(userSignPO.getSignCount().value));
		}
		res.put("signExist", signExist);
		return res;
	}

	 		
	/**
	 * 若是第一次签到,新增签到记录,同时首次签到加积分
	 * @param req
	 * @return
	 * @throws Exception
	 */
	@Service(serviceName = "UserSignService_newSignRecord")
	public IResData newSignRecord(IReqData req) throws Exception {

		log.debug("开始进入 UserSignService_newSignRecord 方法。");

		IPersistenceService dao = SwordPersistenceUtils.getPersistenceService();

		//IPageQueryDAO pdao=PageQueryUtils.getPageQueryDAO(); 

		IResData res = new SwordRes();
		String userid = ReqJsonUtil.getPostParam(req, "userId");
		
		TUserSignPO signPO = new TUserSignPO();
		signPO.setSignId(new DE_SIGN_ID(SwordSequenceUtils.generateRandomString()));
		signPO.setUserid(new DE_USERID(userid));
		signPO.setSignCount(new DE_SIGN_COUNT(1));
		signPO.setSignHistory(new DE_SIGN_HISTORY((long)1));
		final String insertDate = DateFormatUtil.getNowDate();
		signPO.setSignLastmodifytime(new DE_SIGN_LASTMODIFYTIME(insertDate));
		signPO.setExt(new DE_EXT("首次签到，时间："+insertDate));
		int i = dao.insertPO(signPO);
		if (i >= 1) {
			int j = addUserWealthBySign(dao, userid, signPO.getSignCount().value);
			if (j > 0) {
				res.put("signSuccess", "true");
				res.put("wealthValueAdd", j);
				res.put("msg", "该用户第一次签到,成功插入数据！");
			}else {
				res.put("signSuccess", "false");
				res.put("msg", "该用户第一次签到,更新数据失败！");
			}
		} else {
			res.put("signSuccess", "false");
			res.put("msg", "该用户第一次签到,插入数据失败！");
		}
		res.put("todayHaveSigned", "false");
		return res;
	}

	 		
	/**
	 * 若不是第一次签到，调用该公共的用户签到方法
	 * @param req
	 * @return
	 * @throws Exception
	 */
	@Service(serviceName = "UserSignService_commonSign")
	public IResData commonSign(IReqData req) throws Exception {

		log.debug("开始进入 UserSignService_commonSign 方法。");

		IPersistenceService dao = SwordPersistenceUtils.getPersistenceService();
		
		IResData res = new SwordRes();
		String userid = ReqJsonUtil.getPostParam(req, "userId");
		String todayHaveSigned = "true";
		SQLParam param = new SQLParam();
		param.addParam(userid);
		TUserSignPO userSignPO = dao.queryPOByKey("UserSignService_queryUserSignInfoByUserid", param, TUserSignPO.class);
		String lastModifyTime = DateFormatUtil.date2str(userSignPO.getSignLastmodifytime().value,DateFormatUtil.DATE_FORMAT);
		Timestamp lastModifyTimeStamp = new Timestamp(DateFormatUtil.getTimeByDateStr(lastModifyTime, DateFormatUtil.DATE_FORMAT));
		Timestamp todayStartTimeStamp = new Timestamp(DateFormatUtil.getTimeByDateStr(DateFormatUtil.getNowDate(), DateFormatUtil.DATE_FORMAT));
		if (todayStartTimeStamp.after(lastModifyTimeStamp)) {
			//今天没有签过到
			todayHaveSigned = "false";
			//获得几天没有签到的数据，用来更新历史签到记录
			final long missDays= (todayStartTimeStamp.getTime()-new Timestamp((lastModifyTimeStamp.getTime()+1)).getTime())/(24*60*60*1000);
            int newSignCount= userSignPO.getSignCount().value;
            String newExt="签到";
			if (missDays == 0) { 
				// 连续签到，加分，连续签到次数增加1 ，签到历史移动一位
				newSignCount += 1;
				newExt="连续签到"+newSignCount+"天";
			} else {
				// 不连续签到，加分，连续签到次数为1，签到历史移动missDays位
				newSignCount = 1;
				newExt="未连续签到，连续签到天数重置为1";
			}
			// 签到超过6天，连续签到次数重置为1
			if (newSignCount > 6) { 
				newSignCount = 1;
				newExt = "连续签到6天，连续签到天数重置为1，时间："+ DateFormatUtil.timestamp2str(System.currentTimeMillis(),DateFormatUtil.DATE_FORMAT_SFM);
			}
			final long newSignHistory = MoveByteUtil.moveByte(userSignPO.getSignHistory().value, missDays);
			
			//更新用户签到表，并给用户增加相应的财富值
			userSignPO.setSignCount(new DE_SIGN_COUNT(newSignCount));
			userSignPO.setSignHistory(new DE_SIGN_HISTORY(newSignHistory));
			userSignPO.setSignLastmodifytime(new DE_SIGN_LASTMODIFYTIME(DateFormatUtil.getNowDate()));
			userSignPO.setExt(new DE_EXT(newExt));
			int i = dao.updatePO(userSignPO);
			if (i >= 1) {
				int j = addUserWealthBySign(dao, userid, userSignPO.getSignCount().value);
				if (j > 0) {
					res.put("signSuccess", "true");
					res.put("wealthValueAdd", j);
					res.put("msg", "签到成功，成功更新数据！");
				}else {
					res.put("signSuccess", "false");
					res.put("msg", "签到失败，更新数据失败！");
				}
			} else {
				res.put("signSuccess", "false");
				res.put("msg", "签到失败，更新数据失败！");
			}
		}else {
			//今天已经签过到了
			todayHaveSigned = "true";
		}
		
		res.put("todayHaveSigned", todayHaveSigned);
		return res;
	}

	/**
	 * 用户通过签到按一定规则增加财富值
	 * @param dao 数据库操作对象(包含一次数据库连接)
	 * @param userEmail 用户邮箱，唯一
	 * @param signCount 用户连续签到次数
	 * @return 新增的财富值
	 * @throws SwordBaseCheckedException 
	 */
	private int addUserWealthBySign(IPersistenceService dao,String userid,int signCount) throws SwordBaseCheckedException {
		int wealthValueAdd = 0;
		SQLParam param = new SQLParam();
		param.addParam(userid);
		TUserPO userPO = dao.queryPOByKey("UserService_getUserPOByID", param, TUserPO.class);
		// 根据签到规则获得用户要增加的财富值
		int wealth = ScoreRuleUtil.getScoreByRule(signCount, 6);
		userPO.setUserwealth(new DE_USERWEALTH(userPO.getUserwealth().value+wealth));
		int i = dao.updatePO(userPO);
		if (i >= 1) {
			wealthValueAdd = wealth;
		}
		
		return wealthValueAdd;
	}
}